﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Quartz;
using Models;
using Utility;
using Microsoft.Http;
using Common.Logging;
using Service;
using IService;
using Castle.Windsor;

 
namespace ScheduleService.Job
{
    public class UploadOrderJob:JobBase,IJob
    {
        private static readonly ILog Logger = LogManager.GetLogger("UploadOrderJob");
        public void Execute(IJobExecutionContext context)
        {
            try
            {
                Logger.Info("获取上传任务数据");
               // ITestServer ser = new TestServer();
                //ser = Container.Resolve<ITestServer>();
                int count =1;
                int.TryParse(System.Configuration.ConfigurationManager.AppSettings["UploadCount"],out count);
                var list = testService.GetUploasTaskList(count == 0 ? 1 : count);
                foreach (UploadTaskDTO t in list)
                {
                    UploadCase(t.ExamRequestID);
                }
                Logger.Info("上传任务完成");
            }
            catch(Exception ex)
            {
                Logger.Info("病例上传异常");
                Logger.Error("病例上传异常，原因：", ex);
            }
        }

        private void UploadCase(int examRequestID)
        {
            TestServer ser = new TestServer();
            Logger.Info("准备病例数据：" + examRequestID.ToString());
            OrderViewDTO orderView = ser.GetExamRequesByExamID(examRequestID);
            orderView.ServerNode = System.Configuration.ConfigurationManager.AppSettings["ServerNode"].ToString();
            orderView.HospitalCode = System.Configuration.ConfigurationManager.AppSettings["HospitalCode"].ToString();
            Logger.Info("病例数据准备完成，开始上传");
            RegionRespone res = UploadOrderView(orderView);
            Logger.Info("病例数据上传完成,更新上传状态");
            UpdateUploadStatus(res);
            Logger.Info("病例上传成功");
        }

        private RegionRespone UploadOrderView(OrderViewDTO orderView)
        {
            var client = new HttpClient();
            var jsonUtility = new JsonUtility();
            string url = System.Configuration.ConfigurationManager.AppSettings["UploadUrl"].ToString();
            var response = client.Post(url, jsonUtility.GetContent(orderView));
            response.EnsureStatusIsSuccessful();
            var readResult = response.Content.ReadAsString();
            return jsonUtility.Deserialize<RegionRespone>(readResult);
        }

        private void UpdateUploadStatus(RegionRespone res)
        {
            switch (res.StatusCode)
            {
                case 1000://上传成功
                    break;
                case 1001://信息不全
                    break;
                case 1002://数据匹配失败
                    break;
                case 1003://病历已存在
                    break;
                case 1004://更新数据库失败
                    break;
                case 1005://未知错误
                    break;
            }
        }
 
    }
}
